<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import {
  deleteCdnDomainApi,
  getCdnClusterNodeListApi,
  getCdnClusterSiteListApi,
  getCdnDomainListApi,
} from '@/apis/modules/cdn'
import { commonTableProps } from '@/utils/table'
import usePopupPreGetData from '@/views/cdn/node/node-list/hooks/usePopupPreGetData'
import EditorDialog from './dialogs/EditorDialog.vue'
import EditorRemarkDialog from './dialogs/EditorRemarkDialog.vue'
import NodeDetails from './dialogs/NodeDetails.vue'
import SiteDetails from './dialogs/SiteDetails.vue'
import useConfig from './useConfig'

const { tableColumns } = useConfig()

const queryParams = ref({ name_keyword: '' })

const { loading, pagination, data, run } = useListRequest(getCdnDomainListApi, {
  params: queryParams,
  immediate: true,
})

const {
  visible: editorDialogVisible,
  open: openEditorDialog,
  data: editorDialogData,
} = usePopup()

// 删除交换机
function handleDelete(record: any) {
  ModalHelper.error({
    title: '删除域名',
    content: `确定要删除 “ ${record.name || ' -'} ” ？,删除后不会影响已有的解析。`,
    okText: '删除',
    width: 480,
    closable: false,
    onOk: async () => {
      await deleteCdnDomainApi({ id: record.id })
      await run()
      Message.success('删除成功')
    },
  })
}

const appTypeList = computed<OptionItem[]>(() => {
  return data?.value.map(item => ({
    label: item.name,
    value: item.app_id,
    type: item.type,
  }))
})
const {
  visible: editorRemarkDialogVisible,
  open: openEditorRemarkDialog,
  data: editorRemarkDialogData,
} = usePopup()

// 编辑备注
// async function handleSubmitRemark(data: any) {
//   // await updateManageRegionByIdApi(
//   //   pick(data, [
//   //     'id',
//   //     'name',
//   //     'region',
//   //     'region_url',
//   //     'user_name',
//   //     'password',
//   //     'remark',
//   //     'status',
//   //     'country',
//   //   ]),
//   // )
//   // await getList()
//   console.log(data)
//   Message.success('修改成功')
// }

const appStore = useAppStore()
const appList = computed<OptionItem[]>(() => {
  return appStore.appList || []
})

const typeOptions = computed<OptionItem[]>(() => {
  return [
    { label: '接入域名', value: '1' },
    { label: '转换域名', value: '2' },
  ]
})

const { createSortChange } = useTable(run, data)
const onSorterChange = createSortChange(queryParams)

function shouldShowTooltip(remark: string) {
  if (!remark)
    return false
  return remark.length > 50 // 先按字符数快速判断
}

const {
  visible: nodeVisible,
  open: openNode,
  data: nodeData,
  loading: nodeLoading,
  record: nodeRecord,
  pagination: nodePagination,
  run: nodeRun,
} = usePopupPreGetData(getCdnClusterNodeListApi, 'resolve_domain_id')

const {
  visible: siteVisible,
  open: openSite,
  data: siteData,
  loading: siteLoading,
  record: siteRecord,
  pagination: sitePagination,
  run: siteRun,
} = usePopupPreGetData(getCdnClusterSiteListApi, 'resolve_domain_id')
</script>

<template>
  <main-container
    :pagination="false"
    :loading="loading"
    @run="run"
  >
    <template #header>
      <div class="flex space-x-4">
        <a-button
          type="primary"
          @click="openEditorDialog()"
        >
          新建域名
        </a-button>
        <a-input-search
          v-model="queryParams.name_keyword"
          placeholder="请输入域名搜索"
          class="!w-58"
          @change="run()"
          @search="run()"
        />
      </div>
    </template>

    <a-table
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="data"
      @sorter-change="onSorterChange"
    >
      <template #appId="{ record }">
        <div class="descriptions-item__value">
          {{ getOptionLabel(record?.app_id, appList) }}
        </div>
      </template>
      <template #type="{ record }">
        <div class="descriptions-item__value">
          {{ getOptionLabel(record?.type, typeOptions) }}
        </div>
      </template>

      <template #remark="{ record }">
        <div class="flex">
          <a-tooltip
            :content="record.remark || '-'"
            position="top"
            :disabled="!shouldShowTooltip(record.remark)"
          >
            <span class="overflow-hidden text-ellipsis whitespace-nowrap">
              {{ record.remark || '-' }}
            </span>
          </a-tooltip>
          <div class="ml-1 min-w-4 shrink-0">
            <i-icons-edit
              class="table-icon"
              size="16px"
              @click="openEditorRemarkDialog(record)"
            />
          </div>
        </div>
      </template>

      <template #node_count="{ record }">
        <div class="flex items-center gap-x-1 leading-5">
          {{ record.node_count }}
          <a-tooltip
            v-if="record.node_count > 0"
            content="关联节点"
            :show-arrow="false"
          >
            <!-- <i-icons-base-info
              class="cursor-pointer text-7 hover:text-2"
              @click="openNode(record)"
            /> -->
            <i-icons-base-info
              class="table-icon"
              size="16px"
              @click="openNode(record)"
            />
          </a-tooltip>
        </div>
      </template>
      <template #site_count="{ record }">
        <div class="flex items-center gap-x-1 leading-5">
          {{ record.site_count }}
          <a-tooltip
            v-if="record.site_count > 0"
            content="关联站点"
            :show-arrow="false"
          >
            <!-- <i-icons-base-info
              class="cursor-pointer text-7 hover:text-2"
              @click="openSite(record)"
            /> -->
            <i-icons-base-info
              class="table-icon"
              size="16px"
              @click="openSite(record)"
            />
            <!-- <a-link @click="openSite(record)">
              详情
            </a-link> -->
          </a-tooltip>
        </div>
      </template>

      <template #actions="{ record }">
        <a-link
          :hoverable="false"
          @click="openEditorDialog(record)"
        >
          <i-icons-edit size="16px" />
        </a-link>
        <a-link
          :hoverable="false"
          status="danger"
          @click="handleDelete(record)"
        >
          <i-icons-delete size="16px" />
        </a-link>
      </template>
    </a-table>
  </main-container>

  <editor-dialog
    v-model:visible="editorDialogVisible"
    :record="editorDialogData"
    :app-type-list="appTypeList"
    @reload="run"
  />
  <editor-remark-dialog
    v-model:visible="editorRemarkDialogVisible"
    :record="editorRemarkDialogData"
    @reload="run"
  />

  <node-details
    v-if="nodeVisible"
    v-model:visible="nodeVisible"
    v-model:data="nodeData"
    v-model:pagination="nodePagination"
    :record="nodeRecord"
    :loading="nodeLoading"
    :run="nodeRun"
  />
  <site-details
    v-if="siteVisible"
    v-model:visible="siteVisible"
    v-model:data="siteData"
    v-model:pagination="sitePagination"
    :record="siteRecord"
    :loading="siteLoading"
    :run="siteRun"
  />
</template>

<style scoped>
:deep(.arco-table-tr) {
  .table-icon {
    opacity: 0;
    color: var(--color-text-7);
    cursor: pointer;
  }

  &:hover {
    .table-copy-text {
      @apply text-primary;
    }

    .table-icon {
      opacity: 1;
      color: #00a65b;
    }
  }
}
</style>
